package cn.ld.fj.web.order;

import cn.ld.fj.entity.DeskShop;
import cn.ld.fj.entity.Food;
import cn.ld.fj.entity.MealOrder;
import cn.ld.fj.entity.MealOrderFood;
import cn.ld.fj.pojo.MealOrderFoodPojo;
import cn.ld.fj.service.desk.DeskShopManager;
import cn.ld.fj.service.food.FoodManager;
import cn.ld.fj.service.food.FoodTypeManager;
import cn.ld.fj.service.order.MealOrderFoodManager;
import cn.ld.fj.service.order.MealOrderManager;
import cn.ld.fj.util.RequestParamterUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import net.esoar.modules.orm.Page;
import net.esoar.modules.orm.PropertyFilter;
import net.esoar.modules.utils.web.struts2.Struts2Utils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by zuohao on 2017/8/3.
 */

@Controller
@RequestMapping("mealOrderController")
public class MealOrderController {

    @Autowired
    private MealOrderFoodManager mealOrderFoodManager;

    @Autowired
    private MealOrderManager mealOrderManager;

    @Autowired
    private FoodManager foodManager;
    @Autowired
    private DeskShopManager deskShopManager;

    private Page<MealOrderFood> page = new Page<MealOrderFood>(10);

    @RequestMapping("mealOrderFoodList")
    @ResponseBody
    public Object MealOrderFoodList(HttpServletRequest request){
        List<MealOrderFoodPojo> mealOrderFoodPojos = Lists.newArrayList();
        String deskShopId=request.getParameter("deskShopId");
        //查询桌子状态
        DeskShop deskShop=deskShopManager.getOne(Long.valueOf(deskShopId));
        int deskStatus=0;
        if (deskShop!=null){
            deskStatus=deskShop.getStatus();
        }
        List<MealOrder> mealOrderList=mealOrderManager.findBy("deskShopId",Long.valueOf(deskShopId));
        MealOrder mealOrder=new MealOrder();
        Map<String,Object> resultMap=new HashMap<>();
        if (mealOrderList!=null && mealOrderList.size()>0) {
           mealOrder = mealOrderList.get(0);
           //未结账或未离桌显示订单，结账且离桌不显示订单
            if(deskStatus!=1||mealOrder.getOrderType()!=2){
                List<MealOrderFood> mealOrderFoods = mealOrderFoodManager.findListFood(mealOrder.getId());
                if (CollectionUtils.isNotEmpty(mealOrderFoods)) {
                    for (MealOrderFood mealOrderFood : mealOrderFoods) {
                        MealOrderFoodPojo mealOrderFoodPojo = new MealOrderFoodPojo();
                        BeanUtils.copyProperties(mealOrderFood, mealOrderFoodPojo);

                        Food food = foodManager.getOne(mealOrderFood.getFoodId());
                        if (food != null) {
                            mealOrderFoodPojo.setFoodName(food.getFoodName());
                            mealOrderFoodPojo.setPrice(food.getPrice());
                            mealOrderFoodPojo.setDisCountPrice(food.getDisCountPrice());
                        }

                        mealOrderFoodPojos.add(mealOrderFoodPojo);
                    }
                }
                resultMap.put("mealOrderList",mealOrder);
            }
//        for (MealOrder mealOrder:mealOrderList) {

//        }
        }
        resultMap.put("mealOrderFoodPojos",mealOrderFoodPojos);
        return resultMap;
    }

    @RequestMapping("updateOrderTypeById")
    @ResponseBody
    public Object updateOrderTypeById(@RequestParam("mealOrderId")Long mealOrderId){
        MealOrder mealOrder=mealOrderManager.getOne(mealOrderId);
        mealOrder.setOrderType(2);
        mealOrderManager.save(mealOrder);
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("status","success");
        return resultMap;
    }

    @RequestMapping("updateMealOrderByDeskId")
    @ResponseBody
    public Object updateMealOrderByDeskId(HttpServletRequest request){
        String deskShopId=request.getParameter("desk_shop_id");
        String personNum=request.getParameter("person_num");
        String totalMoney=request.getParameter("total_money");
        String userId=request.getParameter("user_id");
        String disCountMoney=request.getParameter("dis_count_money");
        String payType=request.getParameter("pay_type");
        String realMoney=request.getParameter("real_money");
        String extra=request.getParameter("extra");
        String type=request.getParameter("type");
        String status="";
        if (type.equals("new")) {
            MealOrder mealOrder = new MealOrder();
            mealOrder.setDeskShopId(Long.valueOf(deskShopId));
            mealOrder.setDisCountMoney(Long.valueOf(disCountMoney));
            mealOrder.setOrderType(1);//1 就餐中   2 已结账   3欠账
            mealOrder.setPayType(Integer.valueOf(payType));
            mealOrder.setRealMoney(Float.valueOf(realMoney));
            mealOrder.setTotalMoney(Float.valueOf(totalMoney));
            mealOrder.setExtra(extra);
            mealOrder.setPersonNum(Integer.valueOf(personNum));
            mealOrder.setCreateDate(new Date());
            mealOrderManager.save(mealOrder);
            long mealOrderId = mealOrder.getId();
            String mealOrderFoods = request.getParameter("mealOrderFoods");
            JSONArray jsonArr = JSON.parseArray(mealOrderFoods);
            for (Object json : jsonArr) {
                Map<String, Object> jsonMap = JSON2Map(json.toString());
                MealOrderFood mealOrderFood = new MealOrderFood();
                mealOrderFood.setFoodId(Long.valueOf(jsonMap.get("food_id").toString()));
                mealOrderFood.setFoodTaste(jsonMap.get("food_taste").toString());
                mealOrderFood.setNum(Integer.valueOf(jsonMap.get("num").toString()));
                mealOrderFood.setRemark(jsonMap.get("remark").toString());
                mealOrderFood.setOrderId(mealOrderId);
                mealOrderFoodManager.save(mealOrderFood);
            }
            status="下单成功";
        } else if (type.equals("add")){
            //判断订单是否是当前订单，当前订单需为未结账订单
            String hql="from cn.ld.fj.entity.MealOrder mo where mo.deskShopId = "+deskShopId+" and orderType = 1 ";
            MealOrder mealOrder=mealOrderManager.find(hql).get(0);
            float oldDisCountMoney=mealOrder.getDisCountMoney();
            float newDisCountMoney=addFloat(oldDisCountMoney,Float.valueOf(disCountMoney));
            float oldTotalMoney=mealOrder.getTotalMoney();
            float newTotalMoney=addFloat(oldTotalMoney,Float.valueOf(totalMoney));
            float oldRealMoney=mealOrder.getRealMoney();
            float newRealMoney=addFloat(oldRealMoney,Float.valueOf(realMoney));
            long mealOrderId=mealOrder.getId();
            mealOrder.setDisCountMoney(newDisCountMoney);
            mealOrder.setTotalMoney(newTotalMoney);
            mealOrder.setRealMoney(newRealMoney);
            mealOrder.setExtra(extra);
            String mealOrderFoods = request.getParameter("mealOrderFoods");
            JSONArray jsonArr = JSON.parseArray(mealOrderFoods);
            List<MealOrderFood> mealOrderFoodList=mealOrderFoodManager.findBy("orderId",mealOrderId);
            for (Object json : jsonArr) {
                Map<String, Object> jsonMap = JSON2Map(json.toString());
                long foodId=Long.valueOf(jsonMap.get("food_id").toString());
                //保存前需要根据mealOrderId,foodId判断是否已存在
                boolean flag=false;
                MealOrderFood mealOrderFood = null;
                for (MealOrderFood mealOrderFood1:mealOrderFoodList){
                    if (mealOrderFood1.getFoodId().longValue()==foodId){
                        mealOrderFood1.setNum(mealOrderFood1.getNum()+Integer.valueOf(jsonMap.get("num").toString()));
                        mealOrderFood1.setRemark(jsonMap.get("remark").toString());
                        mealOrderFood=mealOrderFood1;
                        flag=true;
                        break;
                    }
                }
                if (!flag) {
                    mealOrderFood = new MealOrderFood();
                    mealOrderFood.setFoodId(foodId);
                    mealOrderFood.setFoodTaste(jsonMap.get("food_taste").toString());
                    mealOrderFood.setNum(Integer.valueOf(jsonMap.get("num").toString()));
                    mealOrderFood.setRemark(jsonMap.get("remark").toString());
                    mealOrderFood.setOrderId(mealOrderId);
                }
                mealOrderFoodManager.save(mealOrderFood);
            }
            status="加菜成功";
        } else if (type.equals("del")){
            //判断订单是否是当前订单，当前订单需为未结账订单
            String hql="from cn.ld.fj.entity.MealOrder mo where mo.deskShopId = "+deskShopId+" and orderType = 1 ";
            MealOrder mealOrder=mealOrderManager.find(hql).get(0);
            float oldDisCountMoney=mealOrder.getDisCountMoney();
            float newDisCountMoney=subtractFloat(oldDisCountMoney,Float.valueOf(disCountMoney));
            float oldTotalMoney=mealOrder.getTotalMoney();
            float newTotalMoney=subtractFloat(oldTotalMoney,Float.valueOf(totalMoney));
            float oldRealMoney=mealOrder.getRealMoney();
            float newRealMoney=subtractFloat(oldRealMoney,Float.valueOf(realMoney));
            long mealOrderId=mealOrder.getId();
            mealOrder.setDisCountMoney(newDisCountMoney);
            mealOrder.setTotalMoney(newTotalMoney);
            mealOrder.setRealMoney(newRealMoney);
            mealOrder.setExtra(extra);
            String mealOrderFoods = request.getParameter("mealOrderFoods");
            JSONArray jsonArr = JSON.parseArray(mealOrderFoods);
            List<MealOrderFood> mealOrderFoodList=mealOrderFoodManager.findBy("orderId",mealOrderId);
            for (Object json : jsonArr) {
                Map<String, Object> jsonMap = JSON2Map(json.toString());
                long foodId=Long.valueOf(jsonMap.get("food_id").toString());
                boolean flag=false;
                //保存前需要根据mealOrderId,foodId判断是否已存在，且未上，方可退，后来说不判断了
                for (MealOrderFood mealOrderFood1:mealOrderFoodList){
                    flag=false;
                    if (mealOrderFood1.getFoodId().longValue()==foodId){
//                        if (mealOrderFood1.getNum()>0&&mealOrderFood1.getFoodStatus().intValue()==1){//后来说不判断了
                        if (mealOrderFood1.getNum()>1){     //数量大于1，减
                            int num=Integer.valueOf(jsonMap.get("num").toString());
                            if (mealOrderFood1.getNum()-num>0) {
                                mealOrderFood1.setNum(mealOrderFood1.getNum() - num);
                                mealOrderFoodManager.save(mealOrderFood1);
                            } else {
                                System.out.println("退菜数量大于现有数量");
                                status+="【"+jsonMap.get("food_id")+"】退菜数量大于现有数量\n";
                            }

                        } else if (mealOrderFood1.getNum()>0){  //数量等于1，删
                            mealOrderFoodManager.delete(mealOrderFood1.getId());
                        } else {
                            System.out.println("原有数量统计有误");
                            status+="【"+jsonMap.get("food_id")+"】原有数量统计有误\n";
                        }
                        flag=true;
                        break;
                    }
                }
                if (!flag){//目前菜单没有这道菜，无法退菜
                    System.out.println("目前菜单没有【"+jsonMap.get("food_id")+"】这道菜，无法退菜");
                    status+="目前菜单没有【"+jsonMap.get("food_id")+"】这道菜，无法退菜\n";
                }
            }
            status+="退菜成功";
        }

        return status;
    }


    public Map<String, Object> JSON2Map(String text) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject jsonObject = JSONObject.parseObject(text);
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            map.put(entry.getKey(), entry.getValue());
        }
        return map;
    }

    private float addFloat(float a,float b){
        BigDecimal a1 = new BigDecimal(Float.toString(a));
        BigDecimal b1 = new BigDecimal(Float.toString(b));
        return a1.add(b1).floatValue();
    }
    private float subtractFloat(float a,float b){
        BigDecimal a1 = new BigDecimal(Float.toString(a));
        BigDecimal b1 = new BigDecimal(Float.toString(b));
        return a1.subtract(b1).floatValue();
    }

}
